﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace blackhouse.WebNemo.Business.Groups {
    public class RecordFile {

        #region Fields

        private IGroupRecord record;
        private string column;
        private RecordFileOperation fileOperation;
        private bool lazzyLoaded = false;
        private RecordFileData data;

        #endregion

        #region Properties

        private RecordFileOperation FileOperation {
            get {
                if (this.fileOperation == null)
                    this.fileOperation = RecordFileOperation.Get(this.record, this.column);
                return this.fileOperation;
            }
        }

        public string FileName {
            get {
                this.EnsureFileDataLoaded();
                return this.data.FileName;
            }
        }

        public Guid FileGuid {
            get {
                this.EnsureFileDataLoaded();
                return this.data.Hash;
            }
        }

        public long FileSize {
            get {
                this.EnsureFileDataLoaded();
                return this.data.Size;
            }
        }

        public bool Exist {
            get {
                this.EnsureFileDataLoaded();
                return this.data.Exist;
            }
        }


        #endregion

        #region Constructors

        public RecordFile(IGroupRecord record, string column) {
            this.record = record;
            this.column = column;
        }

        #endregion

        #region Methods

        private void EnsureFileDataLoaded() {
            if (!this.lazzyLoaded) {
                this.data = this.FileOperation.GetInfo();
                this.lazzyLoaded = true;
            }
        }

        public bool SaveFile(string fileName, Stream fileStream) {
            RecordFileData data = new RecordFileData();
            data.FileName = this.FormatFileName(fileName);
            data.Size = fileStream.Length;
            data.Hash = Guid.NewGuid();
            data.Exist = false;
            return this.FileOperation.SaveFile(data, fileStream);
        }

        private string FormatFileName(string oryginalFileName) {
            string extension = oryginalFileName.Split('.').Last();
            oryginalFileName = oryginalFileName.ReplaceEx("." + extension, "").CleanStringForUrl().RemovePolishChars().RemovePunctuation() + "." + extension;
            return oryginalFileName;
        }

        public byte[] GetData() {
            return this.FileOperation.GetFileData();
        }

        #endregion

    }
}
